//
//  ShopBuildViewController.m
//  LazyCat
//
//  Created by jike on 15/12/12.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "ShopBuildViewController.h"
#import "MyHeaderTableViewCell.h"
#import "MyMessTableViewCell.h"
#import "AFNetworkHandler.h"

@interface ShopBuildViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    UITableView *_tableView;
    UIImage *headerImg;
    UIButton *_doneBtn;
    
    NSString *shopName; // 超市名称
    NSString *shortintroduce; // 超市简介
    NSString *shopnote; // 超市公告
    NSString *contacter; // 联系人
    NSString *mobile; // 电话

}

@end

@implementation ShopBuildViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     
    [self initNav:@"店铺设置" doBack:YES];
    
     shopName = [AppData share].shopname;
     shortintroduce = [AppData share].shortintroduce;
     shopnote = [AppData share].shopnote;
     contacter = [AppData share].contacter;
     mobile = [AppData share].mobile;
    
    [self createTable];
    
}
-(void)createTable
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.scrollEnabled = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [_tableView addGestureRecognizer:tap];
    
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.navBar addGestureRecognizer:tap1];
    
    _doneBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _doneBtn.frame = CGRectMake(10, 410, ScreenWidth - 20, 40);
    _doneBtn.backgroundColor = MainColor;
    _doneBtn.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    _doneBtn.layer.cornerRadius = 5;
    _doneBtn.clipsToBounds = YES;
    [_doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_doneBtn setTitle:@"保存" forState:UIControlStateNormal];
    [_doneBtn addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_doneBtn];
    
    // 预览
    //    UIButton *yulanButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth - 50, 30, 30, 20)];
//    [yulanButton setBackgroundImage:[UIImage imageNamed:@"yulan"] forState:UIControlStateNormal];
//    yulanButton.adjustsImageWhenHighlighted = NO;
//    [yulanButton addTarget:self action:@selector(yulanAction) forControlEvents:UIControlEventTouchUpInside];
//    [self.navBar addSubview:yulanButton];
    
    
    
}


//#pragma mark - 预览点击方法
//-(void)yulanAction
//{
//
//}


// 回收键盘
-(void)tapAction{
 
    
    [self.view endEditing:YES];
    
    
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    
 
    //设置动画的名字
    [UIView beginAnimations:@"Animation" context:nil];
    //设置动画的间隔时间
    [UIView setAnimationDuration:0.20];
    //??使用当前正在运行的状态开始下一段动画
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置视图移动的位移
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - 100, self.view.frame.size.width, self.view.frame.size.height);
    //设置动画结束
    [UIView commitAnimations];
 
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 9;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 70;
    }else{
        return 50;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 4;
    }else{
        return 2;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyHeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    MyMessTableViewCell *bcell = [tableView dequeueReusableCellWithIdentifier:@"dcell"];
    
    NSArray *titleArr = [NSArray arrayWithObjects:@"超市名称",@"超市简介",@"超市公告",@"联系人",@"手机号码", nil];
    if (!cell) {
          cell = [[[NSBundle mainBundle] loadNibNamed:@"MyHeaderTableViewCell" owner:self options:nil] firstObject];
    }
    if (!bcell) {
        bcell =  [[[NSBundle mainBundle] loadNibNamed:@"MyMessTableViewCell" owner:self options:nil] firstObject];
    }
        bcell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0 && indexPath.row == 0) { // 上传logo
        if (headerImg) {
            cell.headerImg.image = headerImg;
        }else{
            
            [cell.headerImg sd_setImageWithURL:[NSURL URLWithString:[[ShopCommonModel share].shoplogo safeString]] placeholderImage:[UIImage imageNamed:@"touxiang.png"]];
             
            
        }
        UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 70)];
        [cell addSubview:lab];
        lab.userInteractionEnabled = YES;
 
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(logoAction)];
        [lab addGestureRecognizer:tap];
        return cell;
    }else{
        if (indexPath.section == 0) {
            bcell.titleLable.text = titleArr[indexPath.row - 1];
            if (indexPath.row == 1) { // 超市名称
                if ([AppData share].shopname.length < 1) {
                     bcell.inputTextField.placeholder = @"请输超市名称";
                }else{
                bcell.inputTextField.placeholder = @"请输超市名称";
                bcell.inputTextField.text = [AppData share].shopname;
                }
                bcell.inputTextField.tag = 100;
                bcell.inputTextField.enabled = YES;
                bcell.jiantouImg.hidden = YES;
            }else if(indexPath.row == 2){ // 超市简介
                
                if (![[AppData share].shortintroduce isEqualToString:@""]) {
                     bcell.inputTextField.placeholder = @"请输入超市简介";
                    bcell.inputTextField.text = [AppData share].shortintroduce;
                }else{
                    bcell.inputTextField.placeholder = @"请输入超市简介";
                }
                bcell.inputTextField.tag = 200;
                bcell.jiantouImg.hidden = YES;
            }else if (indexPath.row == 3){ // 超市公告
                if (![[AppData share].shopnote isEqualToString:@""]) {
                    bcell.inputTextField.placeholder = @"请输入公告内容";
                    bcell.inputTextField.text = [AppData share].shopnote;
                }else{
                   bcell.inputTextField.placeholder = @"请输入公告内容";
                }
                bcell.inputTextField.tag = 300;
                bcell.jiantouImg.hidden = YES;
            }
        }else if(indexPath.section == 1){
            bcell.titleLable.text = titleArr[indexPath.row + 3];
            if (indexPath.row == 0) { // 联系人
                if ([AppData share].contacter.length < 1) {
                    bcell.inputTextField.placeholder = @"请输入联系人";
                }else{
                     bcell.inputTextField.placeholder = @"请输入联系人";
                  bcell.inputTextField.text = [AppData share].contacter;
                }
                
                bcell.inputTextField.enabled = YES;
                bcell.jiantouImg.hidden = YES;
                bcell.inputTextField.tag = 400;
            }else if (indexPath.row == 1){ // 手机号
                if ([AppData share].mobile.length < 1) {
                    bcell.inputTextField.placeholder = @"请输入手机号";
                }else{
                    bcell.inputTextField.placeholder = @"请输入手机号";
                  bcell.inputTextField.text = [AppData share].mobile;
                }
                bcell.inputTextField.enabled = YES;
                bcell.jiantouImg.hidden = YES;
                bcell.inputTextField.tag = 500;
            }

        }
        bcell.inputTextField.delegate = self;
          return bcell;
    }
  
}


-(void)textFieldDidEndEditing:(UITextField *)textField
{
    
    //设置动画的名字
    [UIView beginAnimations:@"Animation" context:nil];
    //设置动画的间隔时间
    [UIView setAnimationDuration:0.20];
    //??使用当前正在运行的状态开始下一段动画
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置视图移动的位移
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y + 100, self.view.frame.size.width, self.view.frame.size.height);
    //设置动画结束
    [UIView commitAnimations];
    if (textField.tag == 100) {
        shopName = textField.text;
    }else if (textField.tag == 200){
        shortintroduce = textField.text;
    }else if (textField.tag == 300){
        shopnote = textField.text;
    }else if (textField.tag == 400){
        contacter = textField.text;
    }else if (textField.tag == 500){
        mobile = textField.text;
    }
    
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        
        
        [[PhotoPickerManager shared] showActionSheetInView:self.view fromController:self completion:^(UIImage *image) {
            headerImg = image;
            [self sendImg];
        } cancelBlock:^{
            
        }];
    }
}
-(void)logoAction
{

    [[PhotoPickerManager shared] showActionSheetInView:self.view fromController:self completion:^(UIImage *image) {
    headerImg = image;
    [self sendImg];
} cancelBlock:^{
    
}];
}

#pragma mark - 保存方法
-(void)saveAction
{
     [self.view endEditing:YES];
    
    NSString * CT = @"^1\\d{10}$";
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
     BOOL res4 = [regextestct evaluateWithObject:mobile];
    
    if (res4) {
        
    }else{
        
        [[MessShowView share] showWithMess:@"输入的号码格式不正确"];
        return;
    }
    
   
    NSString *url  = [NSString stringWithFormat:upShopMessageUrl,[AppData share].username,shortintroduce,shopnote,contacter,mobile,shopName];
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        NSDictionary *dic = result;
        if ([[dic objectForKey:@"r"] isEqualToString:@"T"]) {
            [AppData share].shortintroduce = shortintroduce; // 超市简介
            [AppData share].shopnote = shopnote; // 公告
            [AppData share].shopname = shopName; // 店铺名称
            [AppData share].contacter = contacter; // 联系人
            [AppData share].mobile = mobile; // 手机号
            
            [[MessShowView share] showWithMess:@"修改成功" login:YES];
            
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [[MessShowView share] showWithMess:dic[@"m"] login:NO];
        }
        
        
    }];
    
}

#pragma mark- 上传图片
- (void)sendImg {
    //     手机版本号
    NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
    NSString *iptype = [userDefaul objectForKey:@"iptype"];
    NSString *banben = [userDefaul objectForKey:@"banben"];
    // &terminal=%@&OSVersion=IOS1.0.1
    NSString *url = [NSString stringWithFormat:SendHeaderImg,[AppData share].username,[Utils md5SignStr],iptype,banben];
    [NTNetUtil postImgWithParam:nil requestUrl:url dataArr:@[headerImg] block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        NSLog(@"------%@",dic);
        NSString *suc= dic[@"r"];
        if ([suc isEqualToString:@"T"]) {
            [[MessShowView share] showWithMess:@"上传图片成功"];
            [ShopCommonModel share].shoplogo = dic[@"imgUrl"];
            [_tableView reloadData];
        }else {
            [[MessShowView share] showWithMess:@"上传图片失败"];
        }
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
